<template>
  <div>
    <el-dialog
      title="编辑角色"
      :visible="dialogFormVisible"
      style=""
      @close="close"
    >
      <el-form ref="form" :model="form" style="width: 90%" :rules="rules">
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="description"
        >
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="$emit('update:dialogFormVisible', false)"
        >取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRolesListApi, upDateRolesListApi } from '@/api/settings'
export default {
  name: 'SoleDia',
  props: {
    dialogFormVisible: {
      type: Boolean
    },
    editData: {
      type: Object,
      default: () => {}
    },
    isEdit: {
      type: Boolean
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      formLabelWidth: '80px'
    }
  },
  computed: {},

  watch: {
    // 点击编辑按钮时,接受父组件中的数据
    editData: {
      handler(val) {
        this.form = { ...val, permIds: [] }
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    // 确定按钮触发函数
    addRole() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return this.$message({ type: 'error', message: '请输入正确的内容' })
        }
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 发送添加角色请求
    async doAdd() {
      await addRolesListApi(this.form)
      this.$emit('update:dialogFormVisible', false)
    },
    // 发送修改角色请求
    async doEdit() {
      await upDateRolesListApi(this.form)
      this.$emit('update:dialogFormVisible', false)
    },
    // 弹出框关闭时触发
    close() {
      this.$emit('update:dialogFormVisible', false)
      this.$refs.form.resetFields()
      this.$emit('success')
    }
  }
}
</script>

<style lang="less" scoped></style>
